//
//  XHRecipeViewController.m
//  meiang_edu
//
//  Created by 徐辉 on 2019/1/10.
//  Copyright © 2019年 com.meiang.meiang_edu. All rights reserved.
//

#import "XHRecipeViewController.h"
#import "WGQEdgeInsetsLabel.h"
#import "UIView+ShowView.h"
#import "WGQAlbumTableViewCell.h"

//#import "WGQGrowUpLittleModel.h"
#import "WGQFamilyAlbumModel.h"
#import "LTSCalendarManager.h"

#import "WGQAlbumDateHeaderView.h"
#import "WGQAlbumDateHeaderModel.h"
#import "XHRecipeCollectionViewCell.h"
#import "XHRecipeTableViewCell.h"
#import "XHRecipeModel.h"
#import "WGQGrowUpLittleModel.h"

#import "XHEditRecipeCollectionViewCell.h"
#import "XHEditRecipeTableViewCell.h"

#import "MAJiGouModel.h"

#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
#define RandColor RGBColor(arc4random_uniform(255), arc4random_uniform(255), arc4random_uniform(255))

#define FFColorAlpha(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:0.6]

@interface XHRecipeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * tableArray;
@property (nonatomic,strong) UILabel * saveSuccessLabel;
@property (nonatomic,strong) WGQAlbumDateHeaderView * headerView;
@end

@implementation XHRecipeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = FFColor(0xebebeb);
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.tableArray = [NSMutableArray array];
    if([self.typeStr isEqualToString:@"editRecipe"]){
        self.title = @"编辑菜谱";
    }else{
        self.title = @"查看菜谱";
    }
    [self showPromptLabel];
    [self addSubViews];
    NSDate * date = [NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"yyyy-MM-dd"];
    NSString * dateStr;
    dateStr = [format1 stringFromDate:date];
    [self requestDataWithTime:dateStr];
}

- (void)addSubViews
{
    [self drawRightButton];
    [self drawHeaderView];
    [self drawTableView];
}

- (void)drawHeaderView
{
    WeakSelf(weakSelf);
    self.headerView = [[WGQAlbumDateHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 76 * kScale)];
    [self.view addSubview:self.headerView];
    self.headerView.item_click_block = ^(WGQAlbumDateHeaderModel *model)
    {
        [weakSelf requestDataWithTime:model.dateStr];
    };
}

- (void)requestDataWithTime:(NSString *)time
{
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request)
     {
         request.requestSerializerType = ZBJSONRequestSerializer;
      
         NSString * urlStr =[NSString stringWithFormat:@"http://www.armyant.com.cn:8082/Army/v1.1_menu/list_%@?ddate=%@",self.jigouModel.ID,time];
         request.URLString = urlStr;
         request.methodType = ZBMethodTypeGET;
         [request setValue:userinfo.token forHeaderField:@"token"];
         request.apiType = ZBRequestTypeRefresh;
     } success:^(id responseObject, apiType type)
     {
         [MBManager hideAlert];
         // 解析数据
         NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
         DLog(@"%@",dataDict);
         NSInteger code = [dataDict[@"msgcode"] integerValue];
         if (code == 1)
         {
             // 请求成功
             [MBManager hideAlert];
             if (self.tableArray.count > 0)
             {
                 [self.tableArray removeAllObjects];
             }
             NSArray * array = dataDict[@"value"];
             [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
              {
                  NSDictionary * dict = obj;
                  NSArray * rowArray = dict[@"rows"];
                  NSMutableArray * muarray = [NSMutableArray array];
                  [rowArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
                   {
                       NSDictionary * rowDict = obj;
                       XHRecipeModel * model = [[XHRecipeModel alloc] initWithDictionary:rowDict];
                       [muarray addObject:model];
                   }];
                  
                  id title = [dict objectForKey:@"ctimeblock"];
                  if ([title isKindOfClass:[NSString class]])
                  {
                      [self.tableArray addObject:@{@"title":dict[@"ctimeblock"],@"array":muarray}];
                  }
              }];
             [self.tableView reloadData];
         }
         else
         {
             [MBManager showBriefAlert:dataDict[@"message"]];
         }
     } failure:^(NSError *error)
     {
         DLog(@"%@",error);
         
     } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache)
     {
         if (isCache==YES)
         {
             DLog(@"使用了缓存");
         }
     }];
}

- (void)drawTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = FFColor(0xebebeb);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[XHRecipeTableViewCell class] forCellReuseIdentifier:[NSString stringWithUTF8String:object_getClassName([XHRecipeTableViewCell class])]];
    [self.tableView registerClass:[XHEditRecipeTableViewCell class] forCellReuseIdentifier:[NSString stringWithUTF8String:object_getClassName([XHEditRecipeTableViewCell class])]];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 70 * kScale;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.view.mas_left).offset(4 * kScale);
         make.right.equalTo(self.view.mas_right).offset(-4 * kScale);
         make.top.equalTo(self.view.mas_top).offset(76 * kScale);
         make.bottom.equalTo(self.view.mas_bottom);
     }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tableArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if([self.typeStr isEqualToString:@"editRecipe"]){
        XHEditRecipeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithUTF8String:object_getClassName([XHEditRecipeTableViewCell class])] forIndexPath:indexPath];
        
        [cell setObject:self.tableArray[indexPath.section]];
        
        __weak __typeof(&*self)weakSelf = self;
        //图片保存成功的提示
        cell.image_save_success_block = ^(NSString * _Nonnull isSaveSuccess)
        {
            [weakSelf showSuccessText:isSaveSuccess];
        };
        cell.guid = self.jigouModel.ID;
//        cell.image_edit_block = ^(NSInteger index, NSString *titleStr) {
//
//            [cell setObject:self.tableArray[indexPath.section]];
//
//            [weakSelf showSuccessText:titleStr];
//        };
        
        return cell;
    }else{
        XHRecipeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithUTF8String:object_getClassName([XHRecipeTableViewCell class])] forIndexPath:indexPath];
        
        [cell setObject:self.tableArray[indexPath.section]];
        
        __weak __typeof(&*self)weakSelf = self;
        //图片保存成功的提示
        cell.image_save_success_block = ^(NSString * _Nonnull isSaveSuccess)
        {
            [weakSelf showSuccessText:isSaveSuccess];
        };
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 4 * kScale;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)showSuccessText:(NSString *)text
{
    self.saveSuccessLabel = [[UILabel alloc] init];
    self.saveSuccessLabel.text =text;
    self.saveSuccessLabel.textAlignment = NSTextAlignmentCenter;
    self.saveSuccessLabel.backgroundColor = FFColorAlpha(0x333333);
    self.saveSuccessLabel.font = [UIFont fontWithName:kMainFontFormat size:14 * kScale];
    self.saveSuccessLabel.textColor = [UIColor whiteColor];
    self.saveSuccessLabel.layer.masksToBounds = YES;
    self.saveSuccessLabel.layer.cornerRadius = 7 * kScale;
    [self.view addSubview:self.saveSuccessLabel];
    [self.saveSuccessLabel mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.view.mas_left).offset(4 * kScale);
         make.right.equalTo(self.view.mas_right).offset(-4 * kScale);
         make.height.mas_equalTo(42 * kScale);
         make.bottom.equalTo(self.view.mas_bottom).offset(-12 * kScale);
     }];
    
    // 创建NSTimer对象
    NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    // 加入RunLoop中
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)timerAction
{
    [self.saveSuccessLabel removeFromSuperview];
}

- (void)drawRightButton
{
    //右上角的按钮
    UIButton * rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 0.0, 35.0, 35.0)];
    [rightBtn addTarget:self action:@selector(rightBtnActionWithSender:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"reminderbutton_logo"] forState:UIControlStateNormal];
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 35.0, 35.0)];
    [view addSubview:rightBtn];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = rightItem;

}

//右上角按钮的点击事件
- (void)rightBtnActionWithSender:(UIButton *)sender
{
    [self showPromptLabel];
}

- (void)showPromptLabel
{
    //蒙版
    WGQEdgeInsetsLabel * promptLabel = [[WGQEdgeInsetsLabel alloc] init];
    promptLabel.contentInset = UIEdgeInsetsMake(0, 12 * kScale, 0, 12 * kScale);
    promptLabel.text = @"如果您需要删除或添加卡片内容，\n请长按您所需要操作的卡片";
    promptLabel.numberOfLines = 2;
    promptLabel.backgroundColor = FFColor(0xffffff);
    promptLabel.font = [UIFont fontWithName:kMainFontFormat size:14 * kScale];
    promptLabel.textColor = FFColor(0x666666);
    promptLabel.layer.masksToBounds = YES;
    promptLabel.layer.cornerRadius = 7 * kScale;
    [promptLabel showWithFrame:CGRectMake(100 * kScale, 72 * kScale, 236 * kScale, 63 * kScale)];
}

@end
